home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 5904 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.2 KB  |  88 lines

  1. Path: news.cis.ohio-state.edu!usenet
  2. From: jun xu <jun@cis.ohio-state.edu>
  3. Newsgroups: comp.lang.c
  4. Subject: Why I can not bind
  5. Date: Wed, 21 Feb 1996 15:55:11 -0500
  6. Organization: The Ohio State University Dept. of Computer and Info. Science
  7. Message-ID: <312B86AF.165F@cis.ohio-state.edu>
  8. NNTP-Posting-Host: crumble.cis.ohio-state.edu
  9. Mime-Version: 1.0
  10. Content-Type: text/plain; charset=us-ascii
  11. Content-Transfer-Encoding: 7bit
  12. X-Mailer: Mozilla 2.0 (X11; I; HP-UX A.09.05 9000/715)
  13.  
  14. I am learning to write a simple server using C and
  15. socket routines. I encounter the run time error of
  16. "Unable to bind". Here below is the code. Thanks in
  17. advance for the help. (Actually it is Richard 
  18. Steven's code and not mine)
  19.  
  20. #include <stdio.h>
  21. #include <sys/types.h>
  22. #include <sys/socket.h>
  23. #include <netinet/in.h>
  24. #include <arpa/inet.h>
  25.  
  26. #define SERV_HOST_ADDR "164.107.128.3"
  27. #define SERV_TCP_PORT 8888
  28. char goodword[] = "Hello World";
  29.  
  30. int writen(fd, ptr, nbytes)
  31. int fd;
  32. char *ptr;
  33. int nbytes;
  34. {
  35.   int nleft, nwritten;
  36.   nleft = nbytes;
  37.   while (nleft > 0) {
  38.     nwritten = write(fd, ptr, nleft);
  39.     if (nwritten <= 0)
  40.       return nwritten;
  41.     nleft -= nwritten;
  42.     ptr += nwritten;
  43.   }
  44.   return nbytes - nleft;
  45. }
  46.  
  47. main(argc, argv)
  48. int argc;
  49. char *argv[];
  50. {
  51.   int sockfd, newsockfd, clilen, childpid;
  52.   struct sockaddr_in cli_addr, serv_addr;
  53.   if (sockfd = socket(AF_INET, SOCK_STREAM, 0) < 0) {
  54.     printf("Unable to open socket!");
  55.     exit(1);
  56.   }  
  57.   bzero((char*)&serv_addr, sizeof(serv_addr));
  58.   serv_addr.sin_family = AF_INET;
  59.   serv_addr.sin_addr.s_addr = inet_addr(SERV_HOST_ADDR);
  60.   serv_addr.sin_port = htons(SERV_TCP_PORT);
  61.   if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) <
  62. 0) {
  63.     printf("Unable to bind");
  64.     exit(1);
  65.   }
  66.   listen(sockfd, 5);
  67.   for (;;) {
  68.     clilen = sizeof(cli_addr);
  69.     newsockfd = accept(sockfd, (struct sockaddr*)&cli_addr, &clilen);
  70.     if (newsockfd < 0) {
  71.       printf("Unable to accept");
  72.       exit(1);
  73.     }  
  74.     if ((childpid = fork()) < 0) {
  75.       printf("Unable to fork!");
  76.       exit(1);
  77.     }  
  78.     else if (childpid == 0) {
  79.       close(sockfd);
  80.       if(writen(newsockfd, goodword, 11) != 11) {
  81.     printf("Socket write error");
  82.     exit(1);
  83.       }
  84.       exit(0);
  85.     }
  86.   }
  87. }
  88.